<template>
  <view class="container">
    <!-- 1. 本地图片选择与预览功能 -->
    <view class="section">
      <text class="title">本地图片选择预览</text>
      <button @click="chooseLocalImage" type="primary" class="btn">选择本机图片</button>
      <button @click="previewSelectedImage" type="default" class="btn" :disabled="!selectedImage">预览图片</button>
      <image :src="selectedImage" mode="widthFix" class="image-preview" v-if="selectedImage" />
    </view>

    <!-- 2. 天气预报功能 -->
    <view class="section">
      <text class="title">明天天气预报</text>
      <button @click="getWeather" type="primary" class="btn">获取天气预报</button>
      <view class="weather-card" v-if="tomorrowWeather">
        <text class="weather-item">日期：{{ tomorrowWeather.date }}</text>
        <text class="weather-item">星期：{{ tomorrowWeather.week }}</text>
        <text class="weather-item">最高温：{{ tomorrowWeather.high }}℃</text>
        <text class="weather-item">最低温：{{ tomorrowWeather.low }}℃</text>
      </view>
      <text class="tip" v-if="weatherTip">{{ weatherTip }}</text>
    </view>

    <!-- 3. 网络图片下载功能 -->
    <view class="section">
      <text class="title">网络图片下载</text>
      <button @click="downloadNetImage" type="primary" class="btn">下载网络图片</button>
      <text class="progress-tip" v-if="downloadProgress">下载进度：{{ downloadProgress }}%</text>
      <image :src="downloadedImage" mode="widthFix" class="image-preview" v-if="downloadedImage" />
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      selectedImage: '', // 选中的本地图片路径
      tomorrowWeather: null, // 明天天气预报数据
      weatherTip: '', // 天气提示文字
      downloadProgress: 0, // 图片下载进度
      downloadedImage: '', // 下载后的网络图片路径
      netImageUrl: 'https://cdn.pixabay.com/photo/2025/11/05/20/57/monastery-9939590_1280.jpg', // 网络图片地址
      weatherApiUrl: 'https://t.weather.sojson.com/api/weather/city/101230501' // 天气预报接口
    };
  },
  methods: {
    // 选择本地图片
    chooseLocalImage() {
      uni.chooseImage({
        count: 1, // 仅选择1张图片
        sizeType: ['original', 'compressed'], // 支持原图和压缩图
        sourceType: ['album'], // 仅从相册选择
        success: (res) => {
          this.selectedImage = res.tempFilePaths[0]; // 保存图片路径
          console.log('本地图片选择成功，路径：', this.selectedImage);
        },
        fail: (err) => {
          console.error('本地图片选择失败：', err);
        }
      });
    },

    // 预览选中的图片
    previewSelectedImage() {
      if (!this.selectedImage) return;
      uni.previewImage({
        urls: [this.selectedImage], // 预览图片列表
        current: this.selectedImage // 当前预览图片
      });
    },

    // 获取天气预报
    getWeather() {
      this.weatherTip = '正在获取天气预报...';
      uni.request({
        url: this.weatherApiUrl,
        method: 'GET',
        success: (res) => {
          if (res.statusCode === 200 && res.data.status === 200) {
            const tomorrowData = res.data.data.forecast[1]; // 第2项为明天数据（索引1）
            this.tomorrowWeather = {
              date: tomorrowData.date,
              week: tomorrowData.week,
              high: tomorrowData.high.replace('高温', '').replace('℃', ''),
              low: tomorrowData.low.replace('低温', '').replace('℃', '')
            };
            this.weatherTip = '';
          } else {
            this.weatherTip = '天气预报获取失败，请重试';
            console.error('天气预报接口返回异常：', res.data);
          }
        },
        fail: (err) => {
          this.weatherTip = '网络错误，无法获取天气预报';
          console.error('天气预报请求失败：', err);
        }
      });
    },

    // 下载网络图片
    downloadNetImage() {
      this.downloadProgress = 0;
      const downloadTask = uni.downloadFile({
        url: this.netImageUrl,
        success: (res) => {
          if (res.statusCode === 200) {
            this.downloadedImage = res.tempFilePaths[0]; // 保存下载后的图片路径
            console.log('网络图片下载成功，路径：', this.downloadedImage);
            // 自动预览下载后的图片
            uni.previewImage({
              urls: [this.downloadedImage]
            });
          } else {
            console.error('网络图片下载失败，状态码：', res.statusCode);
          }
        },
        fail: (err) => {
          console.error('网络图片下载失败：', err);
        }
      });

      // 监听下载进度
      downloadTask.onProgressUpdate((progressRes) => {
        this.downloadProgress = progressRes.progress;
        console.log(`图片下载进度：${progressRes.progress}%，已下载：${progressRes.totalBytesWritten}字节，总大小：${progressRes.totalBytesExpectedToWrite}字节`);
      });
    }
  }
};
</script>

<style scoped>
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
}

.section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  display: block;
}

.btn {
  margin-bottom: 20rpx;
}

.image-preview {
  width: 100%;
  height: auto;
  border-radius: 8rpx;
  margin-top: 10rpx;
}

.weather-card {
  margin-top: 20rpx;
  background-color: #f8f9fa;
  padding: 20rpx;
  border-radius: 8rpx;
}

.weather-item {
  display: block;
  font-size: 28rpx;
  margin-bottom: 10rpx;
}

.tip {
  font-size: 28rpx;
  color: #ff4d4f;
  margin-top: 20rpx;
}

.progress-tip {
  font-size: 28rpx;
  margin-top: 20rpx;
  color: #1890ff;
}
</style>